package com.xhs.exception;

import cn.dev33.satoken.exception.SaSignException;
import com.xhs.message.ReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * @desc:
 * @projectName: java-tools-parent
 * @author: xhs
 * @date: 2023-8-19 019 18:52
 * @version: JDK 1.8
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * 参数校验的异常(post)
     *
     * @param ex 异常
     * @return Object
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnResult<Object> methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("参数校验失败(POST):", ex);
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.error("参数校验失败(POST):{}", fieldError.getDefaultMessage());
        return ReturnResult.error(400, fieldError.getDefaultMessage());
    }

    /**
     * 参数校验的异常(get)
     *
     * @param ex 异常
     * @return Object
     */
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public ReturnResult<Object> constraintViolationException(ConstraintViolationException ex) {
        log.error("参数校验失败(GET):", ex);
        StringBuilder errorInfo = new StringBuilder();
        String errorMessage;
        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {
            errorInfo.append(item.getMessage()).append(",");
        }
        errorMessage = errorInfo.substring(0, errorInfo.toString().length() - 1);
        return ReturnResult.error(400, errorMessage);
    }

    /**
     * 全局异常拦截（拦截项目中的所有异常）
     *
     * @param e 异常
     * @return ReturnResult
     */
    @ResponseBody
    @ExceptionHandler
    public ReturnResult<Object> handlerException(Exception e) {
        // 如果是通用业务异常，直接返回给前端
        if (e instanceof CommonException) {
            CommonException ee = (CommonException) e;
            log.error("通用业务异常:", ee);
            return ReturnResult.error(ee.getCode(), ee.getMsg());
        }
        // 接口签名异常
        if (e instanceof SaSignException) {
            SaSignException ee = (SaSignException) e;
            log.error("接口签名异常:", ee);
            return ReturnResult.error(ee.getCode(), ee.getMessage());
        } else {
            log.error("全局异常:", e);
            return ReturnResult.error();
        }
    }
}
